package com.ojoin.trade.t0loan_core.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.utils.paynow.HttpPost;
import com.ojoin.trade.common.utils.paynow.IAccountConst;
import com.ojoin.trade.common.utils.paynow.Packages;
import com.ojoin.trade.common.utils.paynow.ThreeDESEncryptProvider;
import com.ojoin.trade.common.utils.paynow.Unpack;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.SessionUser;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;
import com.ojoin.trade.t0loan_core.utils.TokenUtils;

//TODO:remove
@Controller
@RequestMapping("/iplimit/test")
public class TestController  extends SimpleBaseController {
	private Logger log = LoggerFactory.getLogger(TestController.class);
	
	@Autowired
	private MerchantUserBaseService userService;
	
	@Autowired
	private AccountBaseService accountService;

	@Autowired
	private TbSlPlatformUserService platformUserService;
	
	@Autowired
	private TbMerchantInfoBaseService merchatinfoService;
	
	protected AccountBaseService getAccountService() {
		return accountService;
	}
	
	//查询商户基本户信息
	@ResponseBody
	@RequestMapping(value = "/queryBaseAccountInfo", method = RequestMethod.GET)
	public String queryBaseAccountInfo(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = TradeUtils.getMhtNo(request);
		List accountList = userService.queryPayUserVOByID(mhtno);
		if (!CommonUtils.isSuccess(accountList)) {
			String errormsg = (String)CommonUtils.buildError(accountList).getMessage();
			LogUtils.getT0loanLog().info("mhtno->" + mhtno + JSONUtils.toJSONString(accountList));
			throw new BusinessException(errormsg);
		} else {
			return "mhtno->" + mhtno + JSONUtils.toJSONString(accountList);
		}
	}

	//查询账户信息
	@ResponseBody
	@RequestMapping(value = "/queryAccountInfo", method = RequestMethod.GET)
	public String queryAccountInfo(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = TradeUtils.getMhtNo(request);
		String accType = (String) request.getParameter("accType");
		List accountList = accountService.queryBaseAccountBalance(mhtno, accType);
		if (!CommonUtils.isSuccess(accountList)) {
			String errormsg = (String)CommonUtils.buildError(accountList).getMessage();
			LogUtils.getT0loanLog().info("mhtno->" + mhtno + "accType->" + accType + JSONUtils.toJSONString(accountList));
			throw new BusinessException(errormsg);
		} else {
			return "mhtno->" + mhtno + "accType->" + accType + JSONUtils.toJSONString(accountList);
		}
	}
		
	//金融户开户
	@ResponseBody
	@RequestMapping(value = "/createFinanceAccount", method = RequestMethod.GET)
	public String createFinanceAccount(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = (String) request.getParameter("mhtno");
		if (StringUtils.isEmpty(mhtno))
			mhtno = TradeUtils.getMhtNo(request);
		
		List openFinanceAccountList = accountService.openFinanceAccount(mhtno);
		if (!CommonUtils.isSuccess(openFinanceAccountList)) {
			String errormsg = (String)CommonUtils.buildError(openFinanceAccountList).getMessage();
			LogUtils.getT0loanLog().info("mhtno->" + mhtno + JSONUtils.toJSONString(openFinanceAccountList));
			throw new BusinessException(errormsg);
		} else {
			return JSONUtils.toJSONString("mhtno->" + mhtno + openFinanceAccountList);
		}
	}
	
	//查询账户信息
	@ResponseBody
	@RequestMapping(value = "/queryAccountInfoByAccType", method = RequestMethod.GET)
	public String queryAccountInfoByAccType(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtNo = TradeUtils.getMhtNo(request);
		String accType = (String) request.getParameter("accType");
		if (StringUtils.isEmpty(accType))
			accType = IConstDef.ACCTYPE_FINANCING;
		
		Packages packages = new Packages();
		Unpack unpack = new Unpack();
		Map<String, String> map = new HashMap<String, String>();
		List accountList = null;
		String requestReport = "";
		String funcode = IAccountConst.QUERY_FINANCIALACC_FUC;
		map.put("funcode", funcode);
		map.put("mhtNo", mhtNo);
		map.put("accType", accType);
		requestReport = packages.returnMess(funcode, map);
		requestReport = "requestReport=" + requestReport;
		String xml = HttpPost.http(IAccountConst.IP, requestReport);
		log.info("查询商户{}，尝试查询商户结算户信息", new String[] { mhtNo});
		accountList = unpack.unpack(xml, Constants.ENCODING);
		if (!CommonUtils.isSuccess(accountList)) {
			String errormsg = (String)CommonUtils.buildError(accountList).getMessage();
			log.info("mhtno->" + mhtNo + "accType->" + accType + " 返回->" + JSONUtils.toJSONString(accountList));
			throw new BusinessException(errormsg);
		} else {
			return "mhtno->" + mhtNo + "accType->" + accType + " 返回->" + JSONUtils.toJSONString(accountList);
		}
	}

	//转账(同一商户金融户转至基本户)
	@ResponseBody
	@RequestMapping(value = "/rechargeAccountBalanceNoPwd", method = RequestMethod.GET)
	public String rechargeAccountBalanceNoPwd(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = TradeUtils.getMhtNo(request);
		String amount = (String) request.getParameter("amount");
		String orderId = TokenUtils.generateToken();
		
		List rechargeAcc = accountService.rechargeAccountBalanceNoPwd(mhtno, IConstDef.ACCTYPE_FINANCING, mhtno, IConstDef.ACCTYPE_BASE, amount, "内部转账", orderId);
		if (rechargeAcc == null) {
			return "转账返回为空.";
		} else {
			return "转账返回:" + JSONUtils.toJSONString(rechargeAcc);
		}
	}
	
	//转账（不同商户间）
	@ResponseBody
	@RequestMapping(value = "/rechargeDiffAccountBalanceNoPwd", method = RequestMethod.GET)
	public String rechargeDiffAccountBalanceNoPwd(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno_from = TradeUtils.getMhtNo(request);
		String acctype_from = (String) request.getParameter("acctype_from");
		String mhtno_to = (String) request.getParameter("mhtno_to");
		String acctype_to = (String) request.getParameter("acctype_to");
		String amount = (String) request.getParameter("amount");
		String orderId = TokenUtils.generateToken();
		
		if (StringUtils.isEmpty(acctype_from))
			acctype_from = IConstDef.ACCTYPE_BASE;
		
		if (StringUtils.isEmpty(acctype_to))
			acctype_to = IConstDef.ACCTYPE_BASE;
		
		List rechargeAcc = accountService.rechargeAccountBalanceNoPwd(mhtno_from, IConstDef.ACCTYPE_BASE, mhtno_to, IConstDef.ACCTYPE_BASE, amount, "内部转账", orderId);
		if (rechargeAcc == null) {
			return "转账返回为空.";
		} else {
			return "转账返回:" + JSONUtils.toJSONString(rechargeAcc);
		}
	}
	
	//转账要密码（不同商户间）
	@ResponseBody
	@RequestMapping(value = "/rechargeDiffAccountBalance", method = RequestMethod.GET)
	public String rechargeDiffAccountBalance(HttpServletRequest request,
			HttpServletResponse response) {
		int joinuserid_from = TradeUtils.getJoinId();
		TbMerchantInfo muser_from = merchatinfoService.queryInfoByJoinId(joinuserid_from);
		String mhtno_from = muser_from.getMhtNo();
		
		String acctype_from = (String) request.getParameter("acctype_from");
		
		String joinuserid_to_str = (String) request.getParameter("joinuserid_to");
		TbMerchantInfo muser_to = merchatinfoService.queryInfoByJoinId(CommonUtils.getInt(joinuserid_to_str));
		String mhtno_to = muser_to.getMhtNo();
		
		String acctype_to = (String) request.getParameter("acctype_to");
		String amount = (String) request.getParameter("amount");
		String pwd = (String) request.getParameter("pwd");
		String orderId = TokenUtils.generateToken();
		
		if (StringUtils.isEmpty(acctype_from))
			acctype_from = IConstDef.ACCTYPE_BASE;
		
		if (StringUtils.isEmpty(acctype_to))
			acctype_to = IConstDef.ACCTYPE_BASE;
		
		List rechargeAcc = accountService.rechargeAccountBalance(mhtno_from, acctype_from, pwd, mhtno_to, acctype_to, amount, "内部转账", orderId);
		if (rechargeAcc == null) {
			return "转账返回为空.";
		} else {
			return "转账返回:" + JSONUtils.toJSONString(rechargeAcc);
		}
	}
	
	//提现
	@ResponseBody
	@RequestMapping(value = "/drawAccountBalance", method = RequestMethod.GET)
	public String drawAccountBalance(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = TradeUtils.getMhtNo(request);
		String cardId = (String) request.getParameter("cardId");
		String payPasswd = (String) request.getParameter("payPasswd");
		String amount = (String) request.getParameter("amount");
	try{
	 accountService.drawAccountBalance(mhtno, payPasswd, cardId, amount, "测试提现" + TimeUtils.getCurDateTime());
      return "提现成功";
    }catch (Exception e){
     return "提现失败";
    }

	}
	
	//查询账户余额
	@ResponseBody
	@RequestMapping(value = "/queryAccountBalance", method = RequestMethod.GET)
	public String queryBaseAccountBalance(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = TradeUtils.getMhtNo(request);
		String accType = (String) request.getParameter("accType");
		
		List rechargeAcc = accountService.queryBaseAccountBalance(mhtno, accType);
		if (rechargeAcc == null) {
			return "mhtno->" + mhtno + ", accType->" + accType + " 查询账户余额返回为空.";
		} else {
			return "mhtno->" + mhtno + ", accType->" + accType + "查询账户余额返回:" + JSONUtils.toJSONString(rechargeAcc);
		}
	}
	
	//查询账户余额
	@ResponseBody
	@RequestMapping(value = "/passwordDecrypt", method = RequestMethod.GET)
	public String passwordDecrypt(HttpServletRequest request,
			HttpServletResponse response) {
		String pid = (String) request.getParameter("pid");
		
		TbSlPlatformUser puservo = platformUserService.queryById(Integer.parseInt(pid));
		if (puservo == null)
			return "pid->" + pid + "对应的平台信息为空，请检查.";
		
		int joinuserid = puservo.getIdOfTbMerchantUser();
		TbMerchantInfo userinfovo = merchatinfoService.queryInfoByJoinId(joinuserid);
		if (userinfovo == null)
			return "joinuserid->" + joinuserid + "对应的用户信息为空，请检查.";
		
		String pwd = puservo.getPassword();
		String DSEKey = Config.getProperty("ipaynow.dsekey");// 3DES需要的key
		
		StringBuilder returnstr = new StringBuilder();
		returnstr.append("商户名->" + userinfovo.getMchName() + "\n");
		returnstr.append("手机号->" + userinfovo.getMobile() + "\n");
		returnstr.append("平台名->" + puservo.getPlatformName() + "\n");
		returnstr.append("登陆用户->" + puservo.getUsername() + "\n");
		returnstr.append("登陆密码->" + ThreeDESEncryptProvider.decrypt(pwd, DSEKey) + "\n");
		
		return returnstr.toString();
	}
	
	//查询商户基本户信息
	@ResponseBody
	@RequestMapping(value = "/queryFinanceAccountBanlance", method = RequestMethod.GET)
	public Long queryFinanceAccountBanlance(HttpServletRequest request,
			HttpServletResponse response) {
		String mhtno = TradeUtils.getMhtNo(request);
		Long balance = accountService.queryFinanceAccountBanlance(mhtno);
		
		return balance;
	}
	
	@ResponseBody
    @RequestMapping(value = "/syncRealName", method = RequestMethod.GET)
    public Result syncRealName(HttpServletRequest request,int joinuserid){
        try{
        	merchatinfoService.syncRealName(joinuserid);
            return new Result(Result.Status.OK, "joinuserid->" + joinuserid + "的实名数据更新成功");
        }catch (Exception e){
            log.error("同步实名信息失败",e);
            return new Result(Result.Status.ERROR,"数据更新成功失败" + e.getMessage());
        }
    }
}